package com.karry.yl.service.services.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.karry.commons.base.impl.SuperServiceImpl;
import com.karry.yl.dao.services.RecordsMapper;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.domain.financial.Receipt;
import com.karry.yl.domain.financial.ReceiptItems;
import com.karry.yl.domain.healthdata.HealthData;
import com.karry.yl.domain.services.Items;
import com.karry.yl.domain.services.MealItems;
import com.karry.yl.domain.services.Records;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.financial.ReceiptService;
import com.karry.yl.service.healthdata.HealthDataService;
import com.karry.yl.service.services.ItemsService;
import com.karry.yl.service.services.MealItemsService;
import com.karry.yl.service.services.RecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class RecordsServiceImpl extends SuperServiceImpl<RecordsMapper, Records> implements RecordsService {

    @Autowired
    private HealthDataService healthDataService;
    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private MealItemsService mealItemsService;
    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private ItemsService itemsService;

    @Override
    @Transactional
    public void save(Records records, List<HealthData> healthDataList, Long userId) {
        baseMapper.insert(records);
        Long itemId = records.getItemId();
        if (healthDataList != null && healthDataList.size() > 0) {
            for (HealthData healthData : healthDataList) {
                 if(healthData.getItemId().equals(itemId)){
                     healthData.setRecordsId(records.getId());
                     healthDataService.insert(healthData);
                 }
            }
        }
        //判断该用户是否绑定了套餐，如果未绑定套餐则创建收费单
        Elderly elderly = elderlyService.selectById(records.getElderlyId());
        boolean flag = false;
        if (elderly.getMealId() != null && elderly.getMealId() > 0) {
            List<MealItems> mealItems = mealItemsService.selectList(new EntityWrapper<MealItems>().eq("mealId", elderly.getMealId()));
            for (MealItems mi : mealItems) {
                if (mi.getItemsId().equals(records.getItemId())) {
                    flag = true;
                    break;
                }
            }
        }
        if (!flag) {
            Receipt receipt = new Receipt();
            receipt.setOrgId(records.getOrgId());
            receipt.setOrgName(records.getOrgName());
            receipt.setElderlyId(records.getElderlyId());
            receipt.setElderlyName(records.getElderlyName());
            receipt.setElderlyCode(records.getElderlyCode());
            receipt.setName("服务收费【" + records.getItemName() + "】");
            receipt.setAmount(records.getCost());
            receipt.setStatus(Receipt.STATUS_ZC);
            receipt.setType(Receipt.TYPE_FW);
            receipt.setUserId(userId); //可以知道是哪位护工创建的
            List<ReceiptItems> receiptItemsList = new ArrayList<>();
            ReceiptItems receiptItem = new ReceiptItems();
            receiptItem.setRecordsId(records.getId());
            receiptItem.setCount(1);
            receiptItem.setPrice(records.getCost());
            receiptItem.setMonery(records.getCost());
            receiptItem.setName(records.getItemName());
            receiptItem.setType(ReceiptItems.TYPE_FW);
            receiptItemsList.add(receiptItem);
            receiptService.save(receipt, receiptItemsList);
        }
    }

    @Override
    public void update(Records records, List<HealthData> healthDataList) {
        baseMapper.updateById(records);
        //删除旧的健康数据
        healthDataService.delete(new EntityWrapper<HealthData>().eq("recordsId", records.getId()));
        for (HealthData hd : healthDataList) {
            hd.setRecordsId(records.getId());
            healthDataService.insert(hd);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveData(String records, String healthDatas, Elderly elderly, Long userId, String userName, Long orgId, String orgName) throws Exception {

        final ObjectMapper mapper = new ObjectMapper();
        List<HealthData> healthDataList=new ArrayList<>();
        if (!StringUtils.isEmpty(healthDatas)) {
            if (healthDatas.contains("@")) {
                //包含@就是多个健康数据
                String[] healthDataArray = healthDatas.split("@");
                for (String str : healthDataArray) {
                    Map<String,Object> map = mapper.readValue(str, Map.class);
                    getHealthData(elderly, healthDataList, map);
                }

            } else {
                //只有一条健康数据
                Map<String,Object> map = mapper.readValue(healthDatas, Map.class);
                getHealthData(elderly, healthDataList, map);
            }
        }
        List<Records> recordsList = mapper.readValue(records, new TypeReference<List<Records>>() {
        });
        if (null != elderly) {
            for (Records record : recordsList) {
                record.setUserId(userId);
                record.setUserName(userName);
                record.setElderlyId(elderly.getId());
                record.setElderlyName(elderly.getName());
                record.setOrgId(orgId);
                record.setOrgName(orgName);
                record.setStatus(Records.STATUS_0);
                Items items = itemsService.selectById(record.getItemId());
                record.setItemName(items.getName());
                record.setServiceDate(new Date());
                //健康数据
                this.save(record, healthDataList, userId);
            }
        }


    }

    private void getHealthData(Elderly elderly, List<HealthData> healthDataList, Map<String, Object> map) {
        HealthData healthData = new HealthData();
        healthData.setElderlyId(elderly.getId());
        if(!StringUtils.isEmpty((String) map.get("value"))){
            healthData.setValue((String) map.get("value"));
        }
        if(!StringUtils.isEmpty((String) map.get("standardValues"))){
            healthData.setStandardValues((String) map.get("standardValues"));
        }
        if(!StringUtils.isEmpty((String) map.get("itemId"))){
            healthData.setItemId(Long.parseLong((String) map.get("itemId")));
        }
        if(!StringUtils.isEmpty((String) map.get("healthDataItemId"))){
            healthData.setHealthDataItemId(Long.parseLong((String) map.get("healthDataItemId")));
        }
        if(!StringUtils.isEmpty((String) map.get("healthDataitemName"))){
            healthData.setHealthDataitemName((String) map.get("healthDataitemName"));
        }
        if(!StringUtils.isEmpty((String) map.get("nature"))){
            String nature = (String) map.get("nature");
            boolean flag=false;
            if("1".equals(nature)){
                flag=true;
            }
            healthData.setNature(flag);
        }
        if(!StringUtils.isEmpty((String) map.get("description"))){
            healthData.setDescription((String) map.get("description"));
        }
        healthDataList.add(healthData);
    }
}
